package com.efounder.frame.language;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.util.DisplayMetrics;

import com.alibaba.fastjson.JSONArray;
import com.efounder.mobilemanager.R;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ResourceUtils;

import java.util.List;
import java.util.Locale;

/**
 * 多语言切换的帮助类
 *
 * @author JamesZhang
 */
public class MultiLanguageUtil {

    /**
     * 多语言列表名称
     */
    private static final String MULTI_LANGUAGE_LIST = "multi_language_list.json";

    private static final String TAG = "MultiLanguageUtil";
    private static MultiLanguageUtil instance;
    private Context applicationContext;
    public static final String SAVE_LANGUAGE = "save_language";
    public static List<MultiLanguageModel> multiLanguageModels;

    public static MultiLanguageUtil init(Context mContext) {
        if (instance == null) {
            synchronized (MultiLanguageUtil.class) {
                if (instance == null) {
                    //读取多语言列表Json，每个工程配置的多语言不同，默认从mobileManager中读取
                    String multiLanguageJson = ResourceUtils.readAssets2String(MULTI_LANGUAGE_LIST);
                    multiLanguageModels = JSONArray.parseArray(multiLanguageJson, MultiLanguageModel.class);
                    instance = new MultiLanguageUtil(mContext);
                }
            }
        }
        return instance;
    }

    public static MultiLanguageUtil getInstance() {
        if (instance == null) {
            throw new IllegalStateException("You must be init MultiLanguageUtil first");
        }
        return instance;
    }

    private MultiLanguageUtil(Context context) {
        this.applicationContext = context;
    }

    /**
     * 获取系统的locale
     *
     * @return Locale对象
     */
    public static Locale getSystemLocale(Context context) {
        return MultiLanguageSPUtil.getInstance(context).getSystemCurrentLocal();
    }

    /**
     * 获取当前系统的语言
     *
     * @param context
     */
    public static void saveSystemCurrentLanguage(Context context) {
        Locale locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //7.0以上 返回的是语言列表  内容项可由用户增删，顺序可由用户调整。但是，此接口返回的语言顺序和用户定义的顺序不一定一致！
            locale = LocaleList.getDefault().get(0);
//            for(int i = 0;i<LocaleList.getDefault().size();i++){
//                Log.e("LocaleList","---"+i+"-->"+LocaleList.getDefault().get(i).getCountry());
//            }
        } else {
            locale = Locale.getDefault();
        }
        MultiLanguageSPUtil.getInstance(context).setSystemCurrentLocal(locale);
    }

    /**
     * 获取选择的语言设置
     *
     * @param context
     * @return
     */
    public static Locale getSetLanguageLocale(Context context) {
        //如果不支持多语言，切换系统语言时只返回中文
        if (!EnvSupportManager.isSupportMultiLanguage()) {
            return Locale.CHINA;
        }
        switch (MultiLanguageSPUtil.getInstance(context).getSelectLanguage()) {
            case LanguageType.LANGUAGE_FOLLOW_SYSTEM:
                //如果跟随系统时，系统语言不是应用中包括的，则返回英语
                String countryName = getSystemLocale(context).getCountry();

                return getLocaleByCountry(countryName);
            case LanguageType.LANGUAGE_CHINESE_SIMPLIFIED:
                return Locale.CHINA;
            case LanguageType.LANGUAGE_EN:
                return Locale.US;
            case LanguageType.LANGUAGE_RU:
                return new Locale("ru", "RU");
            case LanguageType.LANGUAGE_HY:
                return new Locale("hy", "HY");
            case LanguageType.LANGUAGE_TH:
                return new Locale("th", "TH");
            case LanguageType.LANGUAGE_ES:
                return new Locale("es", "ES");
            case LanguageType.LANGUAGE_PT:
                return new Locale("pt", "PT");
            case LanguageType.LANGUAGE_ID:
                return new Locale("id", "ID");
            case LanguageType.LANGUAGE_PL:
                return new Locale("pl", "PL");
            case LanguageType.LANGUAGE_KR:
                return new Locale("ko", "KR");
            case LanguageType.LANGUAGE_JP:
                return new Locale("ja", "JP");
            default:
                return Locale.ENGLISH;
        }
    }

    /**
     * 根据Country 缩写  获取 Locale
     *
     * @param countryName
     * @return
     */
    private static Locale getLocaleByCountry(String countryName) {

        boolean isExist = false;
        //配置文件中是否有locale字段
        boolean isLocale = false;
        if (multiLanguageModels != null) {
            //当跟随系统时，如果列表中没有配置，语言没有翻译，
            // 而多语言工具类中支持，会返回string.xml下的中文，
            // 循环多语言列表，判断系统的语言是否在配置的列表，如果在继续执行，如果没有  默认返回英语
            for (MultiLanguageModel languageModel : multiLanguageModels) {
                String locale = languageModel.getLocale();
                if (locale != null) {
                    if (locale.equals(countryName)) {
                        isExist = true;
                    }
                    isLocale = true;
                }
            }
            //如果不存在，并且多语言列表中有local字段，返回英语，否则继续执行下面代码
            if (!isExist && isLocale) {
                return Locale.ENGLISH;
            }
        }

        if (countryName.equals("RU")) {
            return new Locale("ru", "RU");
        } else if (countryName.equals("HY")) {
            return new Locale("hy", "HY");
        } else if (countryName.equals("TH")) {
            return new Locale("th", "TH");
        } else if (countryName.equals("ES")) {
            return new Locale("es", "ES");
        } else if (countryName.equals("PT")) {
            return new Locale("pt", "PT");
        } else if (countryName.equals("ID")) {
            return new Locale("id", "ID");
        } else if (countryName.equals("PL")) {
            return new Locale("pl", "PL");
        } else if (countryName.equals("CN")) {
            return Locale.CHINA;
        }else if(countryName.equals("KR")){
            return new Locale("ko", "KR");
        }else if(countryName.equals("JP")){
            return new Locale("ja", "JP");
        }
        return Locale.ENGLISH;
    }

    /**
     * 获取选择的语言设置
     *
     * @param
     * @return
     */
    public Locale getSetLanguageLocale() {
        int languageType = MultiLanguageSPUtil.getInstance(applicationContext).getSelectLanguage();
        Locale locale = getLocaleByLanguageType(languageType);
        return locale;

//        switch (MultiLanguageSPUtil.getInstance(applicationContext).getSelectLanguage()) {
//            case LanguageType.LANGUAGE_FOLLOW_SYSTEM:
//                return getSystemLocale(applicationContext);
//            case LanguageType.LANGUAGE_CHINESE_SIMPLIFIED:
//                return Locale.CHINA;
//            case LanguageType.LANGUAGE_EN:
//                return Locale.US;
//            case LanguageType.LANGUAGE_RU:
//                return new Locale("ru","RU");
//            case LanguageType.LANGUAGE_HY:
//                return new Locale("hy","HY");
//            case LanguageType.LANGUAGE_TH:
//                return new Locale("th","TH");
//            case LanguageType.LANGUAGE_ES:
//                return new Locale("es","ES");
//            case LanguageType.LANGUAGE_PT:
//                return new Locale("pt","PT");
//            case LanguageType.LANGUAGE_ID:
//                return new Locale("id","ID");
//            case LanguageType.LANGUAGE_PL:
//                return new Locale("pl","PL");
//            default:
//                return Locale.US;
//        }
    }


    /**
     * 根据languagetype获取locale设置
     *
     * @param languageType
     * @return
     */
    public static Locale getLocaleByLanguageType(int languageType) {
        switch (languageType) {
            case LanguageType.LANGUAGE_FOLLOW_SYSTEM:
                return getSystemLocale(AppContext.getInstance());
            case LanguageType.LANGUAGE_CHINESE_SIMPLIFIED:
                return Locale.CHINA;
            case LanguageType.LANGUAGE_EN:
                return Locale.US;
            case LanguageType.LANGUAGE_RU:
                return new Locale("ru", "RU");
            case LanguageType.LANGUAGE_HY:
                return new Locale("hy", "HY");
            case LanguageType.LANGUAGE_TH:
                return new Locale("th", "TH");
            case LanguageType.LANGUAGE_ES:
                return new Locale("es", "ES");
            case LanguageType.LANGUAGE_PT:
                return new Locale("pt", "PT");
            case LanguageType.LANGUAGE_ID:
                return new Locale("id", "ID");
            case LanguageType.LANGUAGE_PL:
                return new Locale("pl", "PL");
            case LanguageType.LANGUAGE_KR:
                return new Locale("ko", "KR");
            case LanguageType.LANGUAGE_JP:
                return new Locale("ja", "JP");
            default:
                return Locale.US;
        }
    }

    /**
     * 更新语言
     *
     * @param languageType
     */
    public void updateLanguage(Context context, int languageType) {
        MultiLanguageSPUtil.getInstance(context).saveLanguage(languageType);
        setApplicationLanguage(context);
//        EventBus.getDefault().post(new OnChangeLanguageEvent(languageType));

        //todo 更新货币单位，反射
//        try {
//            ReflectUtils reflectUtils = ReflectUtils.reflect("com.pansoft.openplanet.manager.CurrencyAndBourseManager");
//            Currency currency = Currency.getInstance(getSetLanguageLocale(AppContext.getInstance()));
//            reflectUtils.method("setCurrencyUnit",currency.getCurrencyCode());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 多语言列表数据
     *
     * @return
     */
    public List<MultiLanguageModel> getLanguageList() {
        int type = MultiLanguageUtil.getInstance().getLanguageType();
        //读取多语言列表Json，每个工程配置的多语言不同，默认从mobileManager中读取
        //循环加载多语言，设置选中语言
        for (MultiLanguageModel multiLanguageModel : multiLanguageModels) {
            //加载当前语言的string.xml文件中key
            String multiLanguageKey = multiLanguageModel.getMultiLanguageKey();
            //加载key对应的字符串
            String languageName = ResStringUtil.getString(ResStringUtil.getResIdByString(R.string.class, multiLanguageKey));
            //设置显示的语言
            multiLanguageModel.setLanguageName(languageName);
            //设置该语言是否被选中
            multiLanguageModel.setSelect(type == multiLanguageModel.getLanguageType());
        }
        return multiLanguageModels;
    }

    /**
     * 获取当前语言名称
     *
     * @return
     */
    public String getCurrentLanguageName() {
        int languageType = MultiLanguageSPUtil.getInstance(applicationContext).getSelectLanguage();
        return getLanguageNameByType(languageType);
//        if (languageType == LanguageType.LANGUAGE_EN) {
//            return applicationContext.getString(R.string.wechat_setting_language_english);
//        } else if (languageType == LanguageType.LANGUAGE_CHINESE_SIMPLIFIED) {
//            return applicationContext.getString(R.string.wechat_setting_simplified_chinese);
//        } else if (languageType == LanguageType.LANGUAGE_ES) {
//            return ResStringUtil.getString(R.string.wechat_setting_language_spanish);
//        } else if (languageType == LanguageType.LANGUAGE_RU) {
//            return ResStringUtil.getString(R.string.wechat_setting_language_russian);
//        } else if (languageType == LanguageType.LANGUAGE_HY) {
//            return ResStringUtil.getString(R.string.wechat_setting_language_armenian);
//        } else if (languageType == LanguageType.LANGUAGE_PT) {
//            return ResStringUtil.getString(R.string.wechat_setting_language_portuguese);
//        } else if (languageType == LanguageType.LANGUAGE_TH) {
//            return ResStringUtil.getString(R.string.wechat_setting_language_thai);
//        } else if (languageType == LanguageType.LANGUAGE_ID) {
//            return ResStringUtil.getString(R.string.wechat_setting_language_indonesia);
//        } else if (languageType == LanguageType.LANGUAGE_PL) {
//            return ResStringUtil.getString(R.string.wechat_setting_language_polish);
//        }
//        return applicationContext.getString(R.string.wechat_setting_language_auto);
    }


    public static String getLanguageNameByType(int languageType) {
        if (languageType == LanguageType.LANGUAGE_EN) {
            return ResStringUtil.getString(R.string.wechat_setting_language_english);
        } else if (languageType == LanguageType.LANGUAGE_CHINESE_SIMPLIFIED) {
            return ResStringUtil.getString(R.string.wechat_setting_simplified_chinese);
        } else if (languageType == LanguageType.LANGUAGE_ES) {
            return ResStringUtil.getString(R.string.wechat_setting_language_spanish);
        } else if (languageType == LanguageType.LANGUAGE_RU) {
            return ResStringUtil.getString(R.string.wechat_setting_language_russian);
        } else if (languageType == LanguageType.LANGUAGE_HY) {
            return ResStringUtil.getString(R.string.wechat_setting_language_armenian);
        } else if (languageType == LanguageType.LANGUAGE_PT) {
            return ResStringUtil.getString(R.string.wechat_setting_language_portuguese);
        } else if (languageType == LanguageType.LANGUAGE_TH) {
            return ResStringUtil.getString(R.string.wechat_setting_language_thai);
        } else if (languageType == LanguageType.LANGUAGE_ID) {
            return ResStringUtil.getString(R.string.wechat_setting_language_indonesia);
        } else if (languageType == LanguageType.LANGUAGE_PL) {
            return ResStringUtil.getString(R.string.wechat_setting_language_polish);
        }else if(languageType == LanguageType.LANGUAGE_KR){
            return ResStringUtil.getString(R.string.wechat_setting_language_korean);
        }else if(languageType == LanguageType.LANGUAGE_JP){
            return ResStringUtil.getString(R.string.wechat_setting_language_japanese);
        }
        return ResStringUtil.getString(R.string.wechat_setting_language_auto);
    }

    /**
     * 获取到用户保存的语言类型
     *
     * @return
     */
    public int getLanguageType() {
        int languageType = MultiLanguageSPUtil.getInstance(applicationContext).getSelectLanguage();
        if (languageType == LanguageType.LANGUAGE_CHINESE_SIMPLIFIED) {
            return LanguageType.LANGUAGE_CHINESE_SIMPLIFIED;
        } else if (languageType == LanguageType.LANGUAGE_FOLLOW_SYSTEM) {
            return LanguageType.LANGUAGE_FOLLOW_SYSTEM;
        } else if (languageType == LanguageType.LANGUAGE_EN) {
            return LanguageType.LANGUAGE_EN;
        }
//        LogUtils.e( "getLanguageType" + languageType);
        return languageType;
    }


    /**
     * 7.0以上系统的语言设置是需要跟随Context上下文来设置的，
     * 我们要在Activity的attachBaseContext中重新attach修改后的context
     */
    public static Context setLocal(Context context) {
        return updateResources(context, getSetLanguageLocale(context));
    }

    private static Context updateResources(Context context, Locale locale) {
        Locale.setDefault(locale);
        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            config.setLocale(locale);

            LocaleList localeList = new LocaleList(locale);
            LocaleList.setDefault(localeList);
            config.setLocales(localeList);

            context = context.createConfigurationContext(config);
        } else {
            config.locale = locale;
            res.updateConfiguration(config, res.getDisplayMetrics());
        }

        //todo yqs
        //setApplicationLanguage(context);

        return context;
    }

    /**
     * 设置语言类型
     */
    public static void setApplicationLanguage(Context context) {
        Resources resources = context.getApplicationContext().getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        Locale locale = getSetLanguageLocale(context);
        config.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(locale);
            LocaleList.setDefault(localeList);
            config.setLocales(localeList);
            context.getApplicationContext().createConfigurationContext(config);
            Locale.setDefault(locale);
        }
        resources.updateConfiguration(config, dm);
    }

    /**
     * 屏幕旋转调用此方法
     *
     * @param context
     */
    public static void onConfigurationChanged(Context context) {
        saveSystemCurrentLanguage(context);
        setLocal(context);
        setApplicationLanguage(context);
    }

}
